import React, { useState, useEffect } from 'react';
import { Form, Row, Col, Card, Button, Select, Input, notification } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import ImageUpload from '../../../components/ImageUpload';
import { ALL, PAGE } from '@/utils/constant';
import { gradesList, getTeacher, editClases } from '@/services/api';

const ref1: any = React.createRef();

interface gradesData {
  status: string;
  data: any;
}

interface UserFormProps extends FormComponentProps {
  gradesData: object[];
  history: object;
  clasesData: {};
}

const { Item } = Form;
const MyForm = Form.create<UserFormProps>()(
  ({
    form: { getFieldDecorator, validateFields, setFieldsValue, resetFields },
    clasesData,
    gradesData,
    history,
  }: any) => {
    const [teracherIdData, setTeracherIdData] = useState([]);
    // const [terachersData, setTerachersData] = useState([]);
    const initGrades = JSON.parse(JSON.stringify(gradesData));
    const formItemLayout = {
      labelCol: {
        xs: { span: 4, offset: 4 },
      },
      wrapperCol: {
        sm: { span: 8 },
      },
    };
    const teachers: any[] = [];
    if (clasesData.teachers) {
      clasesData.teachers.forEach((v: any) => {
        teachers.push(v.user_id);
      });
    }
    const defaultImage: any = [];
    let initImageId = 0;
    if (clasesData.image) {
      const newImage: any = {};
      newImage.uid = clasesData.image.id;
      newImage.url = clasesData.image.url;
      newImage.status = 'done';
      defaultImage.push(newImage);
      initImageId = clasesData.image.id;
    }

    // 这些是可选的， 目前只用得到 imageIds， [1,2,3,3,4]
    const handlerChangeImgIds = (imageIds: any) => {
      imageIds.length
        ? setFieldsValue({ image_id: Number(imageIds.join()) })
        : setFieldsValue({ image_id: undefined });
    };
    // console.log();

    //请求教师数据
    useEffect(() => {
      getTeacher({ page: PAGE, size: ALL }).then((resp: any) => {
        if (resp.status === 'success') {
          setTeracherIdData(resp.data.data);
        }
      });
    }, []);
    return (
      <Form layout="horizontal" {...formItemLayout}>
        <Item label="年级">
          {getFieldDecorator('grade_id', {
            initialValue: clasesData.grade_id,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select
              placeholder="请选择"
              allowClear
              showSearch
              filterOption={(input: any, option: any) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {initGrades.map((item: any) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>,
          )}
        </Item>
        <Item label="班级名称">
          {getFieldDecorator('name', {
            initialValue: clasesData.name,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Item>
        <Item label="选择班主任">
          {getFieldDecorator('teacher_id', {
            initialValue: clasesData.teacher && clasesData.teacher.id,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select
              placeholder="请选择"
              allowClear
              showSearch
              optionFilterProp="children"
              defaultActiveFirstOption={false}
              filterOption={true}
              // defaultValue={clasesData.teacher && clasesData.teacher.id}
              // onSearch={value => {
              //   if (value) {
              //     const searchValue = value.trim();
              //     getTeacher({ page: PAGE, size: 10, keyword: searchValue }).then((resp: any) => {
              //       if (resp.status === 'success') {
              //         setTeracherIdData(resp.data.data);
              //       }
              //     });
              //   }
              // }}
            >
              {/* {clasesData.teacher && (
                <Select.Option value={clasesData.teacher.id} key={clasesData.teacher.id}>
                  {clasesData.teacher.name}
                </Select.Option>
              )} */}
              {teracherIdData.map((item: any) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>,
          )}
        </Item>
        <Item label="老师">
          {getFieldDecorator('teachers', {
            initialValue: teachers,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select
              placeholder="请选择"
              mode="multiple"
              allowClear
              showSearch
              defaultActiveFirstOption={false}
              filterOption={true}
              optionFilterProp="children"

              // onSearch={value => {
              //   if (value) {
              //     const searchValue = value.trim();
              //     getTeacher({ page: PAGE, size: 10, keyword: searchValue }).then((resp: any) => {
              //       if (resp.status === 'success') {
              //         setTerachersData(resp.data.data);
              //       }
              //     });
              //   }
              // }}
            >
              {/* {clasesData.teachers &&
                clasesData.teachers.map((item: any) => (
                  <Select.Option value={item.user_id} key={item.user_id}>
                    {item.name}
                  </Select.Option>
                ))} */}
              {teracherIdData.map((item: any) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>,
          )}
        </Item>
        <Item label="是否开启">
          {getFieldDecorator('status', {
            initialValue: String(clasesData.status),
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select placeholder="请选择">
              <Select.Option value="true" key={1}>
                {' '}
                开启{' '}
              </Select.Option>
              <Select.Option value="false" key={2}>
                {' '}
                关闭{' '}
              </Select.Option>
            </Select>,
          )}
        </Item>
        <Item label="二维码群号">
          {getFieldDecorator('image_id', {
            initialValue: clasesData.image && clasesData.image.id,
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <ImageUpload
              ref={ref1}
              imageLength={1}
              handlerChangeImgIds={handlerChangeImgIds}
              defaultFileList={defaultImage}
            />,
          )}
        </Item>
        <Row className="rowMarginTop">
          <Col offset={8}>
            <Button
              type="primary"
              onClick={() => {
                validateFields((err: any, val: any) => {
                  const newVal = JSON.parse(JSON.stringify(val));
                  if (!err) {
                    if (newVal.status === 'true') {
                      newVal.status = true;
                    } else {
                      newVal.status = false;
                    }
                    newVal.id = clasesData.id;
                    editClases(newVal).then((resp: any) => {
                      if (resp.status === 'success') {
                        notification.success({
                          message: '编辑成功',
                        });
                        history.push('classList');
                      }
                    });
                  }
                });
              }}
            >
              提交
            </Button>
            <Button
              className="secondBtn"
              onClick={() => {
                resetFields();
                setFieldsValue({ image_id: initImageId });
                ref1.current.handlerReset();
              }}
            >
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    );
  },
);

function EditClases({ history }: any) {
  const [gradesData, setGradesData] = useState([]);
  const [clasesData, setClasesData] = useState({});

  useEffect(() => {
    gradesList({ page: PAGE, size: ALL }).then((res: gradesData) => {
      if (res.status === 'success') {
        setGradesData(res.data.data);
      }
    });
    setClasesData(JSON.parse(sessionStorage.getItem('clasesData') || ''));
  }, []);
  return (
    <Card title="编辑班级">
      <MyForm gradesData={gradesData} history={history} clasesData={clasesData} />
    </Card>
  );
}

export default EditClases;
